<template>
  <div v-loading="loading" class="admin-client">
    <div class="header">
      <div class="date">{{ saveTime }}</div>
      <div class="button-group">
        <el-button size="mini" type="primary" @click="saveTemplate">保存</el-button>
        <el-button size="mini" type="primary">发布</el-button>
      </div>
    </div>

    <div class="content">
      <!--  -->
      <card ref="card">
        <card-header
          big-font-size
          :edit-title="editTitle"
          show-icon
          :title="currentTitle"
          @handleEditTitle="editTitle = true"
          @handleInputBlur="headerInputBlur($event, 'editTitle', 'currentTitle')"
        >
          <el-button class="record" size="mini" @click="showRecordDialog">历史记录</el-button>
        </card-header>

        <!-- 使用说明 -->
        <div class="des">
          <el-input
            v-model="template.description"
            :autosize="{ minRows: 2 }"
            class="description"
            placeholder="添加使用说明..."
            type="textarea"
          />
        </div>

        <div id="parameters" class="parameters">
          <card-header
            :edit-title="editFormTitle"
            :title="currentFormTitle"
            @handleEditTitle="editFormTitle = true"
            @handleInputBlur="headerInputBlur($event, 'editFormTitle', 'currentFormTitle')"
          >
            <el-tooltip content="添加表单" placement="top">
              <i class="el-icon-plus" style="cursor: pointer" @click="showFormDialog" />
            </el-tooltip>
          </card-header>

          <div class="parameters-form">
            <div v-show="parameters.length === 0" class="empty">暂无内容</div>
            <div
              v-for="(option, index) in parameters"
              :key="index"
              class="draggable-item"
              :draggable="true"
              @dragenter="dragenter($event, index, 'parameters', 'formDragIndex')"
              @dragover="dragover($event, index)"
              @dragstart="dragstart(index, 'formDragIndex')"
            >
              <img alt="" class="var-icon" src="@/assets/images/variable.png" />
              <div class="var-name">{{ option.varName }}</div>
              <div>·</div>
              <div class="show-name">
                <el-input v-model="option.value" :placeholder="option.showName" />
              </div>
              <div class="is-required">{{ option.isRequired ? '必填' : '' }}</div>
              <!-- 排序 -->
              <el-tooltip content="拖动排序" placement="top">
                <div class="drag-icon">
                  <img alt="" src="@/assets/images/sort.png" style="width: 14px" />
                </div>
              </el-tooltip>
              <!-- 移除 -->
              <el-tooltip content="移除" placement="top">
                <div class="drag-icon" @click="removeFormOption(index)"><i class="el-icon-remove-outline"></i></div>
              </el-tooltip>
            </div>
          </div>
        </div>

        <div class="steps">
          <div
            v-for="(step, index) in steps"
            :id="step.id"
            :key="index"
            class="step"
            :draggable="true"
            @click="handleSelectStepToAddVariable(step.id)"
            @dragenter="dragenter($event, index, 'steps', 'stepDragIndex')"
            @dragover="dragover($event, index)"
            @dragstart="dragstart(index, 'stepDragIndex')"
          >
            <div class="step-header">
              <!-- 标题 -->
              <div v-show="!step.editTitle" class="step-header-title">
                {{ step.name }}
              </div>

              <!-- 编辑标题 input -->
              <div v-show="step.editTitle">
                <el-input
                  ref="step-header-input"
                  v-model="step.name"
                  class="edit-title-input"
                  style="width: 100px"
                  @blur="step.editTitle = false"
                />
              </div>
              <div class="step-right">
                <!-- 编辑标题 icon -->
                <el-tooltip content="编辑标题" placement="top">
                  <div v-show="!step.editTitle" class="header-title-icon" @click="handleStepEditTitle(step, index)">
                    <i class="el-icon-edit-outline"></i>
                  </div>
                </el-tooltip>
                <!-- 插入步骤 icon -->
                <el-tooltip content="插入步骤" placement="top">
                  <div v-show="index !== steps.length - 1" class="header-title-icon" @click="interPlusStep(index)">
                    <i class="el-icon-plus"></i>
                  </div>
                </el-tooltip>
                <!-- 删除步骤 icon -->
                <el-tooltip content="删除此步" placement="top">
                  <div class="header-title-icon" @click="handleDeleteStep(index)">
                    <i class="el-icon-delete"></i>
                  </div>
                </el-tooltip>
                <!-- 排序 icon -->
                <el-tooltip content="拖动排序" placement="top">
                  <div class="header-title-icon">
                    <img alt="" src="@/assets/images/sort.png" style="width: 14px" />
                  </div>
                </el-tooltip>
                <!-- 配置步骤 icon -->
                <el-tooltip content="配置" placement="top">
                  <div class="header-title-icon" @click="handleSelectStep(step)">
                    <i class="el-icon-setting"></i>
                  </div>
                </el-tooltip>
              </div>
            </div>

            <div class="step-content">
              <div class="step-content-header">
                <div class="step-subtitle">{{ generateSubtitle(step) }}</div>
                <el-tooltip content="本步测试" placement="top">
                  <div class="step-test" @click="showTestDialog"><i class="el-icon-caret-right" /></div>
                </el-tooltip>
              </div>
              <div class="step-content-textarea">
                <!-- <el-input v-model="step.content" :autosize="{ minRows: 3, maxRows: 15 }" placeholder="请输入内容" type="textarea" />-->
                <w-textarea :ref="step.id" v-model="step.content" :tools="[]" @add="addTag" />
              </div>
            </div>
          </div>
        </div>

        <div class="plus">
          <el-button icon="el-icon-plus" @click="plusNextStep">添加下一步</el-button>
        </div>

        <!-- 表单收集弹窗 -->
        <form-dialog ref="formPlusDialog" title="编辑变量" @form-change="handleFormChange" />
        <!-- 历史记录弹窗 -->
        <record-dialog ref="recordDialog" :record-list="recordList" />
        <!-- 测试弹窗 -->
        <test-dialog ref="testDialog" />
      </card>

      <card v-for="step in steps" v-show="selectedStep.id === step.id" :key="step.id">
        <div>
          <div class="model-title">{{ step.name }}</div>
          <!-- 问答模型 -->
          <div class="chat-model model" :class="{ disabled: step.modelDisabled }">
            <small-card ref="chatModel" title="问答模型" :var-name="step.name" @change-name="changeVariableName($event, step)">
              <el-select
                ref="model-selector"
                v-model="step.model"
                class="selector"
                clearable
                placeholder="请选择"
                value-key="name"
                @change="onChangeSelection($event, step, true)"
                @clear="clearSelection(step, 'model-selector')"
              >
                <el-option v-for="option in modelOptions" :key="option.value" :label="option.name" :value="option">
                  <div class="option">
                    <img alt="" class="option-prefix" :src="option.img" />
                    <span class="option-name">{{ option.name }}</span>
                    <span class="option-suffix">{{ option.suffix }}</span>
                  </div>
                </el-option>
              </el-select>
            </small-card>
          </div>

          <el-divider />

          <!-- 外接插件 -->
          <div class="search-model model" :class="{ disabled: step.kbDisabled }">
            <small-card ref="searchModel" title="外接插件" :var-name="step.name" @change-name="changeVariableName($event, step)">
              <el-select
                ref="kb-selector"
                v-model="step.model"
                class="selector"
                clearable
                placeholder="请选择"
                value-key="name"
                @change="onChangeSelection($event, step)"
                @clear="clearSelection(step, 'kb-selector')"
              >
                <el-option v-for="option in kbOptions" :key="option.value" :label="option.name" :value="option">
                  <div class="option">
                    <img alt="" class="option-prefix" :src="option.img" />
                    <span class="option-name">{{ option.name }}</span>
                  </div>
                </el-option>
              </el-select>
              <!-- 选择 本地知识库 显示 -->
              <div v-if="step.function.api_name === 'ai_knowledge'" class="select-kb">
                <div class="top">
                  <div class="left">选择知识库</div>
                  <div class="right" style="cursor: pointer"><i class="el-icon-plus"></i></div>
                </div>

                <div class="plus">
                  <el-button @click="handlePlusKb">点击“+”按钮添加知识库</el-button>
                </div>
              </div>
              <!-- 选择 定向网页内容获取 显示 -->
              <div v-if="step.function.api_name === 'web_content'" class="select-url">
                <div class="left">输入网址</div>
                <input v-model="step.function.api_params.url" placeholder="请输入网址" />
              </div>
            </small-card>
          </div>

          <el-divider />

          <!-- 等待用户输入 -->
          <div class="input-model model" :class="{ disabled: step.inputDisabled }">
            <small-card ref="inputModel" :var-name="step.name" @change-name="changeVariableName($event, step)">
              <el-checkbox v-model="pause" @change="inputModelChange($event, step)">暂停并等待用户输入</el-checkbox>
            </small-card>
          </div>

          <el-divider />

          <!-- 公告提示 -->
          <div class="cue-model model" :class="{ disabled: step.cueDisabled }">
            <el-checkbox @change="cueModelChange($event, step)">公告提示（原样输出左侧文字，常用于提示用户下一步操作）</el-checkbox>
          </div>

          <el-divider />

          <!-- 捕获回答，写入word -->
          <div class="doc-model model">
            <el-checkbox v-model="step.function.doc_tags">捕获回答，写入word中</el-checkbox>
          </div>

          <!-- <el-divider />-->

          <!-- 结束流程 -->
          <!--
          <div class="end-model model">
            <el-checkbox v-model="isEnd">结束流程，提供Word下载</el-checkbox>
          </div>
          -->
        </div>
        <kb-dialog ref="kbDialog" @confirm-kb="confirmSelectKb(step)" />
      </card>
      <card v-show="!selectedStep.id">
        <el-empty description="请选择左侧步骤进行配置" />
      </card>

      <!--
        <prompt-words-card ref="promptWords" @selectStep="onSelectStep" @update-step-name="onUpdateCurrentStepName" />
        <model-card ref="model" :step.sync="selectedStep" />
      -->
      <!-- 变量 -->
      <variable-card ref="variable" :variable-list="variableList" @add-var="addVariable" @go-anchor="goAnchor" />
    </div>
  </div>
</template>

<script>
  // import PromptWordsCard from '@/views/adminClient/components/PromptWordsCard.vue'
  // import ModelCard from '@/views/adminClient/components/ModelCard.vue'
  import VariableCard from '@/views/adminClient/components/VariableCard.vue'
  import { getTemplate, getTemplateRecordList } from '@/api/template'
  import RecordDialog from '@/components/RecordDialog.vue'
  import CardHeader from '@/views/adminClient/components/CardHeader.vue'
  import Card from '@/views/adminClient/components/Card.vue'
  import TestDialog from '@/components/TestDialog.vue'
  import FormDialog from '@/components/FormDialog.vue'
  import { numberToChinese } from '@/utils'
  import KbDialog from '@/components/KbDialog.vue'
  import SmallCard from '@/views/adminClient/components/SmallCard.vue'
  import { kbOptions, modelOptions } from '@/views/adminClient/data'

  export default {
    name: 'AdminClient',
    // components: { FormDialog, TestDialog, Card, CardHeader, RecordDialog, VariableCard, ModelCard, PromptWordsCard },
    components: { SmallCard, KbDialog, FormDialog, TestDialog, Card, CardHeader, RecordDialog, VariableCard },
    data() {
      return {
        // ai_chat 问答模型
        // ai_search ai搜索
        // ai_knowledge 本地知识库
        // web_content 定向网页检索
        saveTime: '',
        loading: false,
        recordList: [],
        template: {
          id: '',
          name: '',
          business_code: null,
          business_name: '',
          description: '',
          parameters: [],
          is_enabled: false,
          steps: [],
        },
        selectedStep: {
          id: '',
          name: '',
          order: null,
          dependent: '',
          content: '',
          type: '',
          function: {
            api_name: '',
            api_params: {},
            variable: '',
            doc_tags: false,
          },
        },
        selectedStepIdToAddVariable: '',

        // left card
        currentTitle: '产业园区',
        editTitle: false,
        description: '',

        currentFormTitle: '表单收集',
        editFormTitle: false,
        parameters: [
          { type: 'text', varName: '表单1', showName: '建设单位全称？', isRequired: true, model: '', content: '', value: '' },
          { type: 'text', varName: '表单2', showName: '本项目名称？', isRequired: true, model: '', content: '', value: '' },
          { type: 'text', varName: '所属行业', showName: '本项目所属行业？', isRequired: false, model: '', content: '', value: '' },
        ],
        formDragIndex: null,

        steps: [],
        stepDragIndex: null,

        // middle card
        modelOptions,
        kbOptions,
        pause: false,
        isEnd: false,

        // right card
        // variableList: [],
      }
    },
    computed: {
      variableList() {
        const list = {
          parameters: [],
          input: [],
          ai_chat: [],
          ai_search: [],
          ai_knowledge: [],
          web_content: [],
        }
        this.parameters.forEach((p) => {
          list.parameters.push({
            pid: '',
            name: p.varName,
            doc_tags: false,
          })
        })
        this.steps.forEach((_) => {
          const item = {
            pid: _.id,
            name: _.function.variable,
            doc_tags: _.function.doc_tags,
          }

          if (_.type === 'INPUT') {
            list.input.push(item)
          } else if (_.function.api_name === 'ai_chat') {
            list.ai_chat.push(item)
          } else if (_.function.api_name === 'ai_search') {
            list.ai_search.push(item)
          } else if (_.function.api_name === 'ai_knowledge') {
            list.ai_knowledge.push(item)
          } else if (_.function.api_name === 'web_content') {
            list.web_content.push(item)
          }
        })
        return list
      },
    },
    created() {
      // this.getRecordList()
    },
    deactivated() {
      console.log(document.title, this.template)
    },
    methods: {
      getRecordList() {
        this.loading = true
        getTemplateRecordList()
          .then((res) => {
            this.loading = false
            this.recordList = res
            this.getTemplate()
          })
          .catch((e) => {
            this.loading = false
            console.log(e)
          })
      },
      getTemplate() {
        const id = this.recordList[0].id
        this.loading = true
        getTemplate(id)
          .then((res) => {
            this.loading = false
            this.template = res
          })
          .catch((e) => {
            this.loading = false
            console.log(e)
          })
      },
      saveTemplate() {
        this.saveTime = `保存 ${this.$moment().format('YYYY-MM-DD HH:mm:ss')}`
        this.template.parameters = this.parameters
        // 保存成功后处理step自定义key
        const steps = JSON.parse(JSON.stringify(this.steps))
        steps.forEach((step) => {
          delete step.editTitle
          delete step.model
          delete step.modelDisabled
          delete step.kbDisabled
          delete step.inputDisabled
          delete step.cueDisabled
        })
        this.template.steps = steps
        console.log(this.template)
        // 业务
      },

      // left card
      // 拖动排序
      dragstart(index, dragIndex) {
        this[dragIndex] = index
      },
      dragenter(e, index, list, dragIndex) {
        e.preventDefault()
        // 避免源对象触发自身的dragenter事件
        if (this[dragIndex] !== index) {
          const source = this[list][this[dragIndex]]
          this[list].splice(this[dragIndex], 1)
          this[list].splice(index, 0, source)
          // 排序变化后目标对象的索引变成源对象的索引
          this[dragIndex] = index
        }
        console.log(this[list])
      },
      dragover(e, index) {
        e.preventDefault()
      },
      addVariable(variable) {
        if (!this.selectedStepIdToAddVariable) {
          this.$message.warning('请选择要插入变量的步骤')
          return
        }
        const selectedStepIndex = this.steps.findIndex((s) => s.id === this.selectedStepIdToAddVariable)
        // 添加依赖
        const dependent = this.steps[selectedStepIndex].dependent.split(',')
        variable.pid && dependent.push(variable.pid)
        this.steps[selectedStepIndex].dependent = [...new Set(dependent)].join('')

        this.addTag(variable.name, this.steps[selectedStepIndex])

        // 将变量添加至内容里
        // this.steps[selectedStepIndex].content += `{{x:${variable.name}}}`
        console.log(this.steps)
      },
      goAnchor(id) {
        const anchor = document.getElementById(id)
        anchor.scrollIntoView()
      },

      handleFormChange(form) {
        console.log('form', form)
      },
      headerInputBlur(title, editField, titleField) {
        this[editField] = false
        this[titleField] = title
      },
      handleStepEditTitle(step, index) {
        step.editTitle = true
        this.$nextTick(() => {
          this.$refs[`step-header-input`][index].focus()
        })
      },
      numberToChinese,
      showFormDialog() {
        this.$refs.formPlusDialog.showDialog()
      },
      showRecordDialog() {
        this.$refs.recordDialog.showDialog()
      },
      showTestDialog() {
        this.$refs.testDialog.showDialog()
      },
      addTag(varName, step) {
        this.$refs[step.id][0].addTag(varName)
      },
      removeFormOption(index) {
        this.parameters.splice(index, 1)
      },
      // 添加步骤
      plusNextStep() {
        this.steps.push({
          id: `${new Date().getTime()}`,
          name: '标题',
          order: this.steps.length + 1,
          dependent: '',
          content: '',
          type: '',
          function: {
            api_name: '',
            api_params: {},
            variable: '',
            doc_tags: false,
          },
          // 自定义key
          editTitle: false,
          model: null,
          modelDisabled: false,
          kbDisabled: false,
          inputDisabled: false,
          cueDisabled: false,
        })
        this.$nextTick(() => {
          this.$refs.card.scrollIntoView()
        })
      },
      // 插入步骤
      interPlusStep(index) {
        this.steps.splice(index + 1, 0, {
          id: `${new Date().getTime()}`,
          name: '标题',
          order: index + 1,
          dependent: '',
          content: '',
          type: '',
          function: {
            api_name: '',
            api_params: {},
            variable: '',
            doc_tags: false,
          },
          // 自定义key
          editTitle: false,
          model: null,
          modelDisabled: false,
          kbDisabled: false,
          inputDisabled: false,
          cueDisabled: false,
        })
      },
      // 删除步骤
      handleDeleteStep(index) {
        this.steps.splice(index, 1)
      },
      // 选择步骤进行配置
      handleSelectStep(step) {
        this.selectedStep = step
      },
      handleSelectStepToAddVariable(stepId) {
        this.selectedStepIdToAddVariable = stepId
      },

      // middle card
      onChangeSelection(option, step, isChat = false) {
        step.type = 'API'
        step.function.api_name = option.api_name
        step.function.api_params = {
          [option.params_key]: option.params_value,
        }
        step.function.variable = isChat ? this.$refs.chatModel[0].name : this.$refs.searchModel[0].name
        this.changeDisabled(step)

        // this.setSelectionImage(option, 'model-selector')
        // this.setSelectionImage(option, 'kb-selector')
      },
      confirmSelectKb(kb) {
        console.log(kb)
      },
      changeVariableName(value, step) {
        step.function.variable = value
      },
      setSelectionImage(option, refName) {
        if (!option) {
          // this.$refs['model-selector'].$el.children[0].children[0].setAttribute('style', `background: none;`)
          return
        }
        this.$refs[refName].$el.children[0].children[0].setAttribute(
          'style',
          `
        background: url(${option.img}) no-repeat;
        background-position: 10px center;
        background-size: 20px 20px;
        text-indent: 30px;
        `
        )
      },
      clearSelection(step, refName) {
        step.type = ''
        step.function.api_name = ''
        step.function.api_params = {}
        step.modelDisabled = false
        step.kbDisabled = false
        step.inputDisabled = false
        step.cueDisabled = false
        // this.$refs[refName].$el.children[0].children[0].removeAttribute('style')
      },
      handlePlusKb() {
        this.$refs.kbDialog[0].showDialog()
      },
      inputModelChange(value, step) {
        if (value) {
          step.type = 'INPUT'
          step.function.api_name = ''
          step.function.api_params = {}
          step.modelDisabled = true
          step.kbDisabled = true
          step.inputDisabled = false
          step.cueDisabled = true
        } else {
          step.type = ''
          step.modelDisabled = false
          step.kbDisabled = false
          step.inputDisabled = false
          step.cueDisabled = false
        }
      },
      cueModelChange(value, step) {
        if (value) {
          step.type = 'CUE'
          step.function.api_name = ''
          step.function.api_params = {}
          step.modelDisabled = true
          step.kbDisabled = true
          step.inputDisabled = true
          step.cueDisabled = false
        } else {
          step.type = ''
          step.modelDisabled = false
          step.kbDisabled = false
          step.inputDisabled = false
          step.cueDisabled = false
        }
      },
      changeDisabled(step) {
        if (step.type === 'INPUT') {
          step.modelDisabled = true
          step.kbDisabled = true
          step.inputDisabled = false
          step.cueDisabled = true
        } else if (step.type === 'CUE') {
          step.modelDisabled = true
          step.kbDisabled = true
          step.inputDisabled = true
          step.cueDisabled = false
        } else if (step.type === 'API') {
          if (step.function.api_name === 'ai_chat') {
            step.modelDisabled = false
            step.kbDisabled = true
            step.inputDisabled = true
            step.cueDisabled = true
          } else {
            step.modelDisabled = true
            step.kbDisabled = false
            step.inputDisabled = true
            step.cueDisabled = true
          }
        }
      },
      generateSubtitle(step) {
        let subtitle = ''
        if (step.type === 'INPUT') {
          subtitle = '暂停并等待用户输入'
        } else if (step.type === 'CUE') {
          subtitle = '公告提示'
        } else if (step.function.api_name === 'ai_chat') {
          subtitle = 'AI回答'
        } else if (step.function.api_name === 'ai_search') {
          subtitle = 'AI搜索'
        } else if (step.function.api_name === 'ai_knowledge') {
          subtitle = '知识库检索'
        } else if (step.function.api_name === 'web_content') {
          subtitle = '定向搜索网址'
        }
        return subtitle
      },
    },
  }
</script>

<style scoped lang="scss">
  @import '@/styles/admin-client';
</style>
